// 和登录有关的路由地址 
const express = require("express");
const router = express.Router();
const userModel = require("../models/userModel");
const md5 = require("md5");
const jwt = require('jsonwebtoken')
router.get("/login", (req, res) => {
    res.send("login test");
})
router.post("/checkusername", async (req, res) => {
    // console.log(req.body);  
    // {username:"111"} 
    try {
        let data = await userModel.find(req.body);
        console.log(data);
        if (data.length > 0) {
            // 接收用户名；
            res.json({
                info: "用户名正确",
                status: 1
            })
        }else{
            res.json({
                info: "用户名不正确",
                status: 2
            })
        }

    } catch (err) {
        res.json({
            info: "返还失败",
            status: 0
        })
    }

})


router.post("/checkuser",async (req,res)=>{
    req.body.pwd = md5(req.body.pwd);
    try{
        let data = await userModel.find(req.body);
        if(data.length>0){
            let[{username}] = data;
            let tokenstr =   jwt.sign({},"mytoken",{ expiresIn: '2h' })
            res.json({
                info:"用户名且密码正确",
                username,
                status:1,
                tokenstr
            })
        }else{
            res.json({
                info:"用户名或者密码错误",
                status:2
            })
        }
    }catch(err){
        res.json({
            info:"登录失败",
            status:0
        })
    }
})

module.exports = router;
